package com.base.commons.tools.utils;

import com.base.commons.tools.exception.BaseOfException;
import com.base.commons.tools.vo.DynamicColumnExportDTO;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

public class DynamicExcelExportUtil {

    public static DecimalFormat decimalFormat = new DecimalFormat("0.00");

    /**
     * 下载导出的excel文件
     * @param exportDTO
     * @param response
     */
    public static void downloadFile(DynamicColumnExportDTO exportDTO, HttpServletResponse response){
        try {
            //生成excel对象
            Workbook workbook = DynamicExcelExportUtil.getExportWorkbook(exportDTO.getSheetName(),
                    exportDTO.getTitles(),
                    exportDTO.getColumnNames(),
                    exportDTO.getClazz(),
                    exportDTO.getSubTitles(),
                    exportDTO.getSubColumnNames(),
                    exportDTO.getSubClazz(),
                    exportDTO.getDataList());
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Type", "application/force-download");
            String fileName = String.valueOf(System.currentTimeMillis());
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xls");
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            throw new BaseOfException(e.getMessage());
        }
    }

    /**
     * 下载导出的excel文件
     * @param exportDTO
     * @param response
     */
    public static void downloadFileToLocalPath(DynamicColumnExportDTO exportDTO, HttpServletResponse response){
        try {
            //生成excel对象
            Workbook workbook = DynamicExcelExportUtil.getExportWorkbook(exportDTO.getSheetName(),
                    exportDTO.getTitles(),
                    exportDTO.getColumnNames(),
                    exportDTO.getClazz(),
                    exportDTO.getSubTitles(),
                    exportDTO.getSubColumnNames(),
                    exportDTO.getSubClazz(),
                    exportDTO.getDataList());
            String filePath = "D:\\logs\\test1.xls";
            OutputStream out;
            out = new FileOutputStream(filePath);//文件保存地址
            workbook.write(out);
            out.close();
        } catch (IOException e) {
            throw new BaseOfException(e.getMessage());
        }
    }

    /**
     * 导出Excel (支持一对多)
     *
     * @param sheetName   sheet名称
     * @param titles      列标题列表
     * @param columnNames 待导出字段
     * @param clazz 数据对象类型
     * @param subTitles    子数据集合-列标题列表
     * @param subColumnNames 子数据集合-待导出字段
     * @param subClazz 子数据集合-数据对象类型
     * @param dataList    数据对象集合
     * @return
     */
    public static Workbook getExportWorkbook(String sheetName, List<String> titles, List<String> columnNames,Class<?> clazz,
                                             List<String> subTitles,List<String> subColumnNames, Class<?> subClazz,
                                             List dataList) {
        Workbook wb = new HSSFWorkbook();
        int sheetIndex = 1;
        boolean hasNext = true;
        while(hasNext) {
            //创建sheet
            Sheet sheet = wb.createSheet(sheetName+ sheetIndex);
            //写入标题行
            createTitleRow(wb, sheet, titles, subTitles);
            //写入数据行
            hasNext = createDataRow(wb, sheet, columnNames, clazz, subColumnNames, subClazz, dataList);
            sheetIndex++;
        }

        return wb;
    }

    /**
     * 写入标题行
     * @param wb
     * @param sheet
     * @param titles
     * @param subTitles
     */
    public static void createTitleRow(Workbook wb,Sheet sheet,List<String> titles,List<String> subTitles){
        //创建标题行
        Row row = sheet.createRow(0);
        //设置单元格样式
        CellStyle style = wb.createCellStyle();
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        //创建列标题行
        for (int i = 0; i < titles.size(); i++) {
            Cell cell = row.createCell(i);
            cell.setCellValue(titles.get(i));
            cell.setCellStyle(style);
            sheet.setColumnWidth(i,20*256);
        }

        //创建子集合列标题
        if (!CollectionUtils.isEmpty(subTitles)) {
            int startIndex = titles.size();
            for (int i = 0; i < subTitles.size(); i++) {
                Cell cell = row.createCell(startIndex +i);
                cell.setCellValue(subTitles.get(i));
                cell.setCellStyle(style);
                sheet.setColumnWidth(startIndex +i,20*256);
            }
        }
    }

    /**
     * 写入数据行
     * @param wb
     * @param sheet
     * @param columnNames
     * @param clazz
     * @param subColumnNames
     * @param subClazz
     * @param dataList
     */
    public static boolean createDataRow(Workbook wb,Sheet sheet,List<String> columnNames,Class<?> clazz,
                                     List<String> subColumnNames, Class<?> subClazz,
                                     List dataList){
        boolean hasNext = false;
        try {
            if(!CollectionUtils.isEmpty(dataList)) {
                int writedRows = 0;
                int rowIndex = 0;
                for (int k = 0; k < dataList.size(); k++) {
                    Object data = dataList.get(k);
                    rowIndex += 1;
                    Row row = sheet.createRow(rowIndex);
                    writedRows++; //已写行数加1

                    //子集合数据字段
                    List subDataList = null;
                    if(subClazz!=null) {
                        Field subListField = clazz.getDeclaredField("subDataList");
                        subDataList = getListValueByField(clazz, data, subListField);
                    }
                    //遍历数据
                    for (int i = 0; i < columnNames.size(); i++) {
                        //获取字段
                        Field field = getFieldByName(clazz,columnNames.get(i));
                        String fieldValue = getStringValueByField(clazz, data, field);
                        //写入数据到单元格
                        row.createCell(i).setCellValue(fieldValue);
                        if (!CollectionUtils.isEmpty(subDataList) && subDataList.size() > 1) {
                            sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex + subDataList.size() - 1, i, i));
                        }
                    }

                    int columnIndex = columnNames.size();
                    if (!CollectionUtils.isEmpty(subColumnNames) && !CollectionUtils.isEmpty(subDataList)) {
                        for (int i = 0; i < subDataList.size(); i++) {
                            if (i != 0) {
                                rowIndex += 1;
                                row = sheet.createRow(rowIndex);
                                writedRows++; //已写行数加1
                            }

                            Object subData = subDataList.get(i);
                            //遍历子集合数据
                            for (int j = 0; j < subColumnNames.size(); j++) {
                                //获取字段
                                Field subField = getFieldByName(subClazz,subColumnNames.get(j));
                                String subFieldValue = getStringValueByField(subClazz, subData, subField);
                                //写入数据到单元格
                                row.createCell(columnIndex + j).setCellValue(subFieldValue);
                            }
                        }
                    }

                    //判断已写行数是否超过5万行
                    if (writedRows >= 50000 && k < dataList.size()-1) {
                        //移除dataList中已写入Excel的数据
                        dataList.subList(0, k+1).clear();
                        hasNext = true;
                        break;
                    }
                }
            }
        } catch(Exception e) {
            throw new BaseOfException("下载失败",e);
        }

        return hasNext;
    }

    public static String getStringValueByField(Class<?> clazz, Object data,Field field){
        String value = "";
        try {
            PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
            //获取get方法
            Method getMethod = pd.getReadMethod();
            Object fieldValue = ReflectionUtils.invokeMethod(getMethod, data);
            if (fieldValue == null) {
                fieldValue = "";
            } else {
                if (field.getType() == Date.class) {
                    fieldValue = DateUtils.format((Date) fieldValue, DateUtils.DATE_TIME_PATTERN);
                }
                if (field.getType() == BigDecimal.class) {
                    fieldValue = decimalFormat.format(fieldValue);
                }
            }

            value = fieldValue == null ? "" : fieldValue.toString();
        }catch (Exception e){
            throw new BaseOfException("获取字段值失败",e);
        }
        return value;
    }

    public static List getListValueByField(Class<?> clazz, Object data,Field field){
        List value = null;
        try {
            PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
            //获取get方法
            Method getMethod = pd.getReadMethod();
            Object fieldValue = ReflectionUtils.invokeMethod(getMethod, data);
            if (fieldValue != null) {
                value = (List)fieldValue;
            }
        }catch (Exception e){
            throw new BaseOfException("获取字段值失败",e);
        }
        return value;
    }

    public static Field getFieldByName(Class clazz,String fieldName) throws Exception{
        Field field = null;
        try{
            field = clazz.getDeclaredField(fieldName);
        }catch (Exception e){
            field = clazz.getSuperclass().getDeclaredField(fieldName);
        }
        return field;
    }
}
